package com.bimrun.gis.controller;

import com.bimrun.gis.util.ResourceLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.URISyntaxException;

@RestController
@RequestMapping("/gis-resource")
public class GisResourceController {
    @Autowired
    private ResourceLoader resourceLoader;

    private int writeLength = 20480;

//    @RequestMapping("/image/parameter")
//    public void getGisImage(int level, int x, int y, OutputStream outputStream) throws IOException, URISyntaxException {
//        String key = level + "/" + x + "/" + y;
//        File file = getGisImage(key, outputStream);
//        writeFile(outputStream,file);
//    }

    @RequestMapping("/image")
    public void getGisImage(String key, OutputStream outputStream) throws IOException, URISyntaxException {
        File file = resourceLoader.getImageResource(key);
        writeFile(outputStream, file);
    }

//    @RequestMapping("/terrain/parameter")
//    public void getGisTerrain(int level, int x, int y, OutputStream outputStream) throws IOException, URISyntaxException {
//        String key = level + "/" + x + "/" + y;
//        File file = getGisTerrain(key, outputStream);
//        return file;
//    }

    @RequestMapping("/terrain")
    public void getGisTerrain(String key, OutputStream outputStream) throws IOException, URISyntaxException {
        File file = resourceLoader.getTerrainResource(key);
        writeFile(outputStream, file);
    }


    private void writeFile(OutputStream outputStream, File file) throws IOException {
        Long length = file.length();
        byte[] bytes = new byte[writeLength];

        FileInputStream fio = new FileInputStream(file);

        while (fio.available() != 0) {
            if (length < writeLength) {
                byte[] bytes1 = new byte[length.intValue()];
                fio.read(bytes1);
                outputStream.write(bytes1);
            } else {
                fio.read(bytes);
                outputStream.write(bytes);
            }
            length -= writeLength;
        }
        outputStream.close();
        outputStream.flush();
        fio.close();
    }
}
